<template>
  <el-dialog
    :model-value="distributeDialogVisible"
    title="分配菜单"
    width="30%"
    @close="handleClose"
  >
    <el-input
      v-model="filterText"
      placeholder="Filter keyword"
      style="padding: 5px; margin-bottom: 10px"
      clearable
    />
    <el-scrollbar class="tree">
      <el-tree
        ref="treeRef"
        :data="data"
        show-checkbox
        node-key="id"
        :props="treeProps"
        highlight-current
        accordion
        :default-expanded-keys="defaultExpandedKeys"
        :default-checked-keys="checkedKeysByRoleId"
        :filter-node-method="filterNode"
      />
    </el-scrollbar>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">Cancel</el-button>
        <el-button type="primary" @click="handleConfirm">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from 'vue'
import { doAssign } from '@/api/authority.js'
import { ElMessage } from 'element-plus'

const filterText = ref('')

const checkedIds = ref([])

const data = ref([])

const treeProps = ref({
  children: 'children',
  label: 'name'
})

const treeRef = ref(null)

watch(filterText, (val) => {
  treeRef.value.filter(val)
})

const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

// 默认展开的菜单项列表
const defaultExpandedKeys = ref([])
// 默认选中的菜单项
const checkedKeysByRoleId = ref([])

const props = defineProps({
  distributeDialogVisible: {
    require: true,
    default: false,
    type: Boolean
  },
  roleMenuList: {
    type: Array,
    default: () => [],
    require: true
  },
  selectRoleId: {
    type: String,
    default: '',
    require: true
  }
})

const emits = defineEmits(['update:modelValue'])

const finalRes = []
const getRoleSelectIds = (arr) => {
  arr.forEach((item) => {
    if (item.select && item.children.length === 0) {
      finalRes.push(item.id)
    } else if (item.children && item.children.length) {
      getRoleSelectIds(item.children)
    }
  })
  return finalRes
}

// 获取默认展开项ids
const getExpandKeys = (arr, init = []) => {
  return arr.reduce((prev, current) => {
    if (current.level === 1) {
      prev.push(current.id)
    } else if (current.children && current.children.length) {
      getExpandKeys(current.children, init)
    }
    return prev
  }, init)
}

watch(
  () => props.roleMenuList,
  () => {
    const roleMenuLists = JSON.parse(JSON.stringify(props.roleMenuList))
    data.value = roleMenuLists
    // 此处有问题获取选中ids
    const getCheckedIds = getRoleSelectIds(roleMenuLists)
    checkedKeysByRoleId.value = getCheckedIds
    defaultExpandedKeys.value = getExpandKeys(roleMenuLists)
  },
  {
    deep: true,
    immediate: true
  }
)

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = async () => {
  // 调用这个方法可以获取当前选中的所有ids，包括半选中
  const treeNodes = treeRef.value.getCheckedNodes(false, true)
  const selectOrhalfSelectNodes = treeNodes.map((item) => item.id)
  const selectRoleId = props.selectRoleId
  // console.log(selectRoleId)
  // console.log(res)
  // 给角色分配菜单
  try {
    await doAssign({ roleId: selectRoleId }, selectOrhalfSelectNodes)
    ElMessage({
      type: 'success',
      duration: 1500,
      message: '更新成功'
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      duration: 1500,
      message: error
    })
  }
  handleClose()
}
</script>

<style lang="scss" scoped>
:global(.el-dialog__header) {
  border-bottom: 1px solid #dcdfe6;
}
.tree {
  overflow: auto;
  height: 230px;
}
</style>
